package com.lx.yygh.hosp.receiver;

import com.lx.yygh.common.constant.MqConst;
import com.lx.yygh.common.service.RabbitService;
import com.lx.yygh.hosp.service.ScheduleService;
import com.lx.yygh.model.hosp.Schedule;
import com.lx.yygh.vo.msm.MsmVo;
import com.lx.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author c先生
 * @date 2022年10月30日 下午 6:04:33
 * @describe
 */
@Repository
public class HospitalReceiver {
    @Autowired
    ScheduleService scheduleService;
    @Autowired
    RabbitService rabbitService;

    //消费order模块发送到RabbitMQ中的消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER})
    )
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        if(null!=orderMqVo.getAvailableNumber()){
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        }else {
            //取消预约更新预约数
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);
            scheduleService.update(schedule);
        }
        //把短信数据发送到RabbitMQ中，给短信模块消费
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            //hosp模块即使消费者也是生产者
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}
